﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace PurchaseOrderS
{
    /// <summary>
    /// AutoPurchaseOrderS.xaml 的交互逻辑
    /// </summary>
    public partial class AutoPurchaseOrderS : Window
    {
        public AutoPurchaseOrderS()
        {
            InitializeComponent();
        }

        DoubleH.Plugins.IPluginHost host = null;
        ObservableCollection<BindingProperty> items = new ObservableCollection<BindingProperty>();
        public void Init(DoubleH.Plugins.IPluginHost host)
        {
            this.host = host;
            InitVar();
            InitEvent();
        }

        private void InitVar()
        {
            checkComboBoxStore.ItemsSource = Table.StoreS.GetList(Table.StoreS.EnumEnable.启用);
            checkComboBoxStore.DisplayMemberPath = "Name";
            checkComboBoxStore.ValueMemberPath = "Id";

            InitDataGrid();
        }

        private void InitEvent()
        {
            productSListInfoObject.LoadingRow += (ss, ee) => { ee.Row.Header = ee.Row.GetIndex() + 1; };
            productSListInfoObject.CellEditEnding += (ss, ee) => { CheckCellEditValue(ee); };

            buttonAuto.Click += (ss, ee) =>
                {
                    if (string.IsNullOrEmpty(checkComboBoxStore.Text))
                    {
                        MessageWindow.Show("请选择仓库");
                        return;
                    }
                    items.Clear();
                    Calc1();
                    Calc2();
                };

            buttonBuildOrder.Click += (ss, ee) =>
                {
                    if (items.Count == 0)
                    {
                        MessageWindow.Show("请生成自动补货");
                        return;
                    }

                    Table.PurchaseOrderS order = new Table.PurchaseOrderS(Table.PurchaseOrderS.EnumFlag.采购订单);
                    ObservableCollection<Table.ProductS> ps = new ObservableCollection<Table.ProductS>();
                    foreach (BindingProperty bp in items)
                    {
                        if (bp.QuantityConfirm == 0)
                            continue;

                        Table.ProductS p = Table.ProductS.GetObject(bp.ProductSId);
                        p._TempQuantity = bp.QuantityConfirm;
                        ps.Add(p);
                    }
                    if (ps.Count == 0)
                    {
                        MessageWindow.Show("没有可补货的商品");
                        return;
                    }

                    order.ProductSList = ps;
                    MainWindow mw = new MainWindow();
                    mw.Init(Table.PurchaseOrderS.EnumFlag.采购订单, order);
                    this.Close();
                    mw.ShowDialog();
                };
        }

        private void CheckCellEditValue(DataGridCellEditEndingEventArgs ee)
        {
            TextBox textBox = ee.EditingElement as TextBox;
            if (textBox == null)
                return;

            double d = 0;
            if (!double.TryParse(textBox.Text, out d))
                textBox.Undo();
            else
                if (d < 0)
                    textBox.Undo();
        }

        private void Calc1()
        {
            if (radioButton1.IsChecked != true)
                return;

         ObservableCollection<Table.ProductSIO> psio = Table.ProductSIO.GetList(DateTime.Now.AddDays(-integerUpDownDay.Value.Value),DateTime.Now,true, GetStoreSId(),null,Table.ProductSIO.EnumEnable.入账);
            foreach (Table.ProductSIO ps in psio)
            {
                if (items.Count(f => { return f.ProductSId == ps.ProductSId; }) != 0)
                    continue;

                Table.ProductS product = Table.ProductS.GetObject(ps.ProductSId);
                Debug.Assert(product != null);

                BindingProperty bp = new BindingProperty();
                bp.ProductSId = ps.ProductSId;
                bp.StoreSId = ps.StoreSId;

                bp.Barcode = product.Barcode;
                bp.Brand = product._BrandName;
                bp.Code = product.Code;
                bp.Place = product._PlaceName;
                bp.ProductSName = product.Name;
                bp.Standard = product.Standard;
                bp.UniqueS = product._UnitName;
                bp.StoreSName = product.GetNameById(Table.StoreS.tableName, ps.StoreSId);

                double quantity = 0;
                foreach (Table.ProductSIO p in psio.Where(fa =>fa.ProductSId == ps.ProductSId ))
                    quantity -= p.Quantity;

                bp.Quantity = Table.ProductSInStoreS.GetQuantity(ps.ProductSId, ps.StoreSId);
                bp.QuantityIn = Table.ProductSIO.GetQuantityIn(ps.StoreSId, ps.ProductSId);
                if (bp.QuantityIn>= quantity)
                    bp.QuantitySuggest = 0;
                else
                    bp.QuantitySuggest = quantity - bp.QuantityIn;

                bp.QuantityConfirm = bp.QuantitySuggest;
                items.Add(bp);
            }
        }

        private void Calc2()
        {
            if (radioButton2.IsChecked != true)
                return;

            ObservableCollection<Table.ProductSInStoreS> psio = Table.ProductSInStoreS.GetListWhereSetQuantityMax(GetStoreSId());
            foreach (Table.ProductSInStoreS ps in psio)
            {
                if (items.Count(f => { return f.ProductSId == ps.ProductSId; }) != 0)
                    continue;

                Table.ProductS product = Table.ProductS.GetObject(ps.ProductSId);
                Debug.Assert(product != null);

                BindingProperty bp = new BindingProperty();
                bp.ProductSId = ps.ProductSId;
                bp.StoreSId = ps.StoreSId;

                bp.Barcode = product.Barcode;
                bp.Brand = product._BrandName;
                bp.Code = product.Code;
                bp.Place = product._PlaceName;
                bp.ProductSName = product.Name;
                bp.Standard = product.Standard;
                bp.UniqueS = product._UnitName;
                bp.StoreSName = product.GetNameById(Table.StoreS.tableName, ps.StoreSId);

                double quantity = (ps.QuantityMax-ps.QuantityMin)/2;

                bp.Quantity = Table.ProductSInStoreS.GetQuantity(ps.ProductSId, ps.StoreSId);
                bp.QuantityIn = Table.ProductSIO.GetQuantityIn(ps.StoreSId, ps.ProductSId);
                if (bp.QuantityIn + bp.Quantity > quantity)
                    bp.QuantitySuggest = 0;
                else
                    bp.QuantitySuggest = quantity - bp.QuantityIn - bp.Quantity;

                bp.QuantityConfirm = bp.QuantitySuggest;

                items.Add(bp);
            }
        }

        private Int64[] GetStoreSId()
        {
            ObservableCollection<Int64> lt = new ObservableCollection<long>();
            foreach (string str in checkComboBoxStore.SelectedValue.Split(','))
                lt.Add(Int64.Parse(str));

            return lt.ToArray();
        }

        private void InitDataGrid()
        {
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("StoreSName"), Header = "仓库" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("Quantity"), Header = "库存" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("QuantityIn"), Header = "在途数量" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("QuantitySuggest"), Header = "建议补货数量" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { Binding = new Binding("QuantityConfirm"), Header = "补货数量" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("ProductSName"), Header = "名称" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("Code"), Header = "编码" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("Barcode"), Header = "条码" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("UniqueS"), Header = "单位" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("Standard"), Header = "规格" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("Place"), Header = "产地" });
            productSListInfoObject.Columns.Add(new DataGridTextColumn() { IsReadOnly = true, Binding = new Binding("Brand"), Header = "品牌" });

            productSListInfoObject.ItemsSource = items;
        }
    }

    public class BindingProperty
    {
        public Int64 StoreSId { get; set; }
        public string StoreSName { get; set; }
        public double Quantity { get; set; }
        public double QuantityIn { get; set; }
        public double QuantitySuggest { get; set; }
        public double QuantityConfirm { get; set; }
        public Int64 ProductSId { get; set; }
        public string ProductSName { get; set; }
        public string Code { get; set; }
        public string Barcode { get; set; }
        public string UniqueS { get; set; }
        public string Standard { get; set; }
        public string Place { get; set; }
        public string Brand { get; set; }
    }
}
